package SwordFingerOffer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Q37_SerializeTree {


    //序列化与反序列化二叉树
    //先序
    // Encodes a tree to a single string.
    public  String serialize(TreeNode root) {
//        StringBuilder sb = new StringBuilder();
        List<String> list = new ArrayList<>();
        enProcess(root, list);
        return list.toString();
    }

    public void enProcess(TreeNode root, List<String> list) {
        if (root == null){
            list.add("null");
            return;
        }
        list.add(Integer.toString(root.val));
        enProcess(root.left, list);
        enProcess(root.right, list);
    }

    // Decodes your encoded data to tree.
    //"[1,2,3,null,null,4,5]"
    public TreeNode deserialize(String data) {
        //左闭右开 去除[] 分割
        String[] str = data.substring(1, data.length() - 1).replace(" ","").split(",");
        List<String> list =  Arrays.asList(str);
        LinkedList<String> arg = new LinkedList<>(list);
//        TreeNode res = new TreeNode(0);
        return deProcess(arg);
//        return res;
    }

    public TreeNode deProcess(LinkedList<String> list) {

        if (list.size() == 0 || list.peekFirst().equals("null")){
            list.pollFirst();
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(list.pollFirst()));
        node.left = deProcess(list);
        node.right = deProcess(list);
        return node;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        Q37_SerializeTree fun = new Q37_SerializeTree();
        String serialize = fun.serialize(root);
        System.out.println(111);
        TreeNode deserialize = fun.deserialize(serialize);
        System.out.println(deserialize);
    }
}
